<?php

namespace App\Task;

use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use GuzzleHttp\Client;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

class DyMediaLinkTask
{
    protected LoggerInterface $logger;

    public static $getTokenUrl = "https://open.douyin.com/oauth/client_token/";

    public static $getMedialinkUrl = "https://open.douyin.com/api/playlet/v2/video/play_info/";

    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'dymedialink');
    }
    public function execute()
    {
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------开始获取审核通过的短剧');
        //获取需要获取任务的视频

        try {
            $playletData = Playlet::query()->where('album_id','!=',0)->where('album_status',3)->get();
            if($playletData->isNotEmpty()){

                $playletIds = [];

                foreach ($playletData as $playletDatum) {
                    $playletIds[] = $playletDatum->id;
                }
                //查询关联表中的抖音小程序ID
                $this->logger->info('查询关联表中的抖音小程序ID,',$playletIds);
                $appletPlayletRelData = AppletPlayletRel::query()->whereIn('playlet_id',$playletIds)->where(['applet_id' => 20000])->select(['playlet_id','applet_id'])->orderBy('applet_id')->get();
                if($appletPlayletRelData->isNotEmpty()) {
                    $appletIds = array();
                    $appletPlayletKeyVal = array();
                    //遍历获取对应关系和抖音小程序ID
                    foreach ($appletPlayletRelData as $appletPlayletRelDatum){

                        $appletPlayletKeyVal[$appletPlayletRelDatum->playlet_id][] = $appletPlayletRelDatum->applet_id;
                        $appletIds[] = $appletPlayletRelDatum->applet_id;

                    }
                    $appletIds = array_values(array_unique($appletIds));
                    //查询抖音小程序的ID 获取appID 和密钥
                    $this->logger->info('查询抖音小程序的ID 获取appID 和密钥');
                    $appletData = Applet::query()->whereIn('id',$appletIds)->where(['type' => 2])->select(['id','name','app_id','app_secret'])->get();
                    if($appletData->isNotEmpty()) {

                        $appletKeyVal = [];
                        foreach ($appletData as $appletDatum) {
                            $appletKeyVal[$appletDatum->id] = $appletDatum;
                        }
                        foreach ($playletData as $playletDatum) {
                            //短剧名称
                            $playlet_name = $playletDatum->name;
                            //获取对应的抖音小程序accessToken,获取这个短剧绑定的抖音小程序
                            if(empty($appletPlayletKeyVal[$playletDatum->id])){
                                $this->logger->error('获取绑定此短剧的抖音小程序不存在:');
                                continue;
                            }


                            $appletPlayletData = $appletPlayletKeyVal[$playletDatum->id];
                            $appletInfo = array();
                            foreach ($appletPlayletData as $appletPlayletDatum){
                                if(!empty($appletKeyVal[$appletPlayletDatum])){
                                    $appletInfo = $appletKeyVal[$appletPlayletDatum];
                                    break;
                                }
                            }

                            if(empty($appletInfo)){
                                $this->logger->error('获取绑定此短剧的抖音小程序不存在:');
                                continue;
                            }

                            $applet_name = $appletInfo->name;
                            $this->logger->info('获取绑定此短剧的抖音小程序token:'.$applet_name);
                            $accessToken = $this->getDyAccessToken($appletInfo->id,$appletInfo->app_id,$appletInfo->app_secret);

                            if(!empty($appletInfo)) {

                                $this->logger->info('开始获取短剧媒资列');
                                if(!empty($accessToken)){
                                    $this->logger->info('抖音token为:'.$accessToken);
                                    //获取这部剧
                                    $playletEpisodesData = PlayletEpisodes::query()->select(['id','dy_episodes_id','dy_media_status','play_url'])
                                        ->where(['playlet_id' => $playletDatum->id,'dy_media_status' =>3])
                                        ->where('dy_episodes_id','!=',0)->get();
                                    if($playletEpisodesData->isNotEmpty()){

                                        foreach ($playletEpisodesData as $playletEpisodesDatum){

                                            $mediaLink  = $this->getMediaInfo($appletInfo->app_id,$playletDatum->album_id,$playletEpisodesDatum->dy_episodes_id,$accessToken);
//                                            var_dump($mediaLink);

                                            if(!empty($mediaLink)){
                                                $playletEpisodesDatum->dy_original_url = $mediaLink['play_url'];
                                                $playletEpisodesDatum->save();
                                            }else{
                                                $playletEpisodesDatum->dy_original_url = $playletEpisodesDatum->play_url;
                                                $playletEpisodesDatum->save();
                                            }
                                        }
                                    }
                                }else{
                                    $this->logger->error('抖音小程序:'.$applet_name.' 短剧:'.$playlet_name.' 没有对应的token');
                                }

                            }else{
                                $this->logger->error('短剧没有绑定抖音小程序或者短剧没有需要审核的集数');
                            }
                        }
                    }else{
                        $this->logger->error('查询抖音小程序ID：没有对应的抖音小程序数据');
                    }
                }else{
                    $this->logger->error('查询关联表中的抖音小程序ID：没有对应的短剧抖音小程序数据');
                }
            }else{
                $this->logger->info('没有短剧审核数据');
            }
        }catch (\Exception $e){
            $this->logger->error('请求抖音剧目过审后剧集Url|错误：' . $e->getLine() . '|' . $e->getMessage());
        }

        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时审核通过的短剧');
    }
    public function getDyAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('dy');

        $key = 'dy_admin_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'client_key'    => $app_id,
                'client_secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'POST');
            if (!empty($accessTokenInfo['data']['access_token'])){
                $accessToken = $accessTokenInfo['data']['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        return $accessToken;
    }
    public function getMediaInfo($ma_app_id,$album_id,$episode_id,$accessToken){
        $limit = 100;
        $params         = [
            "ma_app_id"    => $ma_app_id,
            "album_id"      => $album_id,
            "episode_id"  => $episode_id,
        ];
        $linkUrl = self::$getMedialinkUrl;
        $this->logger->info('请求抖音播放链接数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求抖音播放链接Url：'.$linkUrl);
        //开始上传
        $result  = $this->request($params, $linkUrl,'POST',$accessToken);
        if($result['err_no'] == 0){

            $this->logger->info('调用抖音播放链接接口成功 返回数据：'.PHP_EOL.var_export(['result' => $result], true));
            return $result['data'];

        }else{
            $this->logger->error('调用抖音播放链接接口失败 返回数据：'.PHP_EOL.var_export(['result' => $result], true));
        }
        return false;
    }
    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}